package com.weasel.weixin.commons.helper;

import com.weasel.weixin.commons.config.CommonConfig;
import com.weasel.weixin.commons.exception.AesException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;

/**
 * Created by Dylan on 2015/10/12.
 */
public final class WeixinEntryptHelper {

    private static String encrypyFormat = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";

    /**
     * 解密
     * @param config  平台的配置
     * @param encryptMsg  需要解密的加密的内容
     * @param timestamp  时间戳
     * @param nonce  随机串
     * @return
     * @throws AesException
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public static String decryptMsg(CommonConfig config,String encryptMsg,String timestamp,String nonce) throws AesException, ParserConfigurationException, IOException, SAXException {

        WXBizMsgCrypt pc = new WXBizMsgCrypt(config.getToken(), config.getEncodingAESKey(), config.getAppid());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        StringReader sr = new StringReader(encryptMsg);
        InputSource is = new InputSource(sr);
        Document document = db.parse(is);

        Element root = document.getDocumentElement();
        NodeList nodelist1 = root.getElementsByTagName("Encrypt");
        NodeList nodelist2 = root.getElementsByTagName("MsgSignature");

        String encrypt = nodelist1.item(0).getTextContent();
        String msgSignature = nodelist2.item(0).getTextContent();

        String fromXML = String.format(encrypyFormat, encrypt);
        String xml = pc.decryptMsg(msgSignature, timestamp, nonce, fromXML);
        return xml;
    }


    /**
     *
     * @param config
     * @param decryptMsg
     * @param timestamp
     * @param nonce
     * @return
     * @throws AesException
     */
    public static String encryptMsg(CommonConfig config,String decryptMsg,String timestamp,String nonce) throws AesException {

        WXBizMsgCrypt pc = new WXBizMsgCrypt(config.getToken(), config.getEncodingAESKey(), config.getAppid());
        String encryptMsg = pc.encryptMsg(decryptMsg, timestamp, nonce);
        return encryptMsg;
    }

    private WeixinEntryptHelper() {
    }
}
